package com.example.course_mangger_system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.course_mangger_system.entity.Student;
import com.example.course_mangger_system.mapper.StudentMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 学生
 * @author: hyj
 * @date: 2023/11/25 15:59
 */
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 添加学生
     *
     * @param student
     * @return
     */
    public int save(Student student) {
        try {
            int result = studentMapper.insert(student);

            // 更新缓存
            updateCache(student.getName() + student.getCourseName());
            return result;
        } catch (Exception e) {
            // 处理异常，可以记录日志或者返回特定的错误码
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 删除学生
     *
     * @param id
     * @return
     */
    public int delete(Long id) {
        Student student = studentMapper.selectById(id);
        int result = studentMapper.deleteById(id);

        // 更新缓存
        updateCache(student.getName() + student.getCourseName());

        return result;
    }

    /**
     * 更新学生
     *
     * @param student
     * @return
     */
    public int update(Student student) {
        int result = studentMapper.updateById(student);

        // 更新缓存
        updateCache(student.getName() + student.getCourseName());

        return result;
    }

    /**
     * 查询学生
     *
     * @param student
     * @return
     */

    public List<Student> list(Student student) {
        String cacheKey = "student:" + student.getName() + student.getCourseName();

        // 尝试从缓存中获取数据
        List<Student> cachedStudent = (List<Student>) redisTemplate.opsForValue().get(cacheKey);

        // 如果缓存中有数据，直接返回
        if (cachedStudent != null) {
            return cachedStudent;
        }

        // 如果缓存中没有数据，从数据库查询
        LambdaQueryWrapper<Student> queryWrapper = Wrappers.lambdaQuery(student);
        List<Student> students = studentMapper.selectList(queryWrapper);

        // 将查询结果存入缓存，设置适当的过期时间
        redisTemplate.opsForValue().set(cacheKey, students);

        return students;
    }

    /**
     * 根据ID查询学生
     *
     * @param id
     * @return
     */
    public Student getById(Long id) {
        return studentMapper.selectById(id);

    }


    private void updateCache(String student) {
        String cacheKey = "student:" + student;

        // 清除缓存
        redisTemplate.delete(cacheKey);
    }
}